<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        background="#5094f3"
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      :search-histories="searchHistories"
      v-else
      @search="onSearch"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchResult from "./components/search-result";
import SearchHistory from "./components/search-history";
import SearchSuggestion from "./components/search-suggestion";
import { setItem, getItem } from "@/utils/storage";

export default {
  name: "Search",
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistories: getItem("TOUTIAO-HISTORY-LIST") || [],
    };
  },
  methods: {
    onSearch(value) {
      console.log(value);
      this.searchText = value;
      this.isResultShow = true;
      //存储到历史记录
      let setArr = new Set(this.searchHistories); //没有重复的内容
      setArr.delete(value); //如果存在则会被删掉
      setArr.add(value); //添加最新的值
      setArr = Array.from(setArr); //变回数组
      this.searchHistories = setArr.reverse();
    },
    onCancel() {
      //   console.log("取消");
      this.$router.back();
    },
  },
  components: {
    SearchResult,
    SearchHistory,
    SearchSuggestion,
  },
  watch: {
    searchHistories: {
      handler() {
        setItem("TOUTIAO-HISTORY-LIST", this.searchHistories);
      },
    },
  },
};
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
